import React, { useState, useEffect } from "react";
import { Table, Button, DatePicker, message } from "antd";
import axios from "axios";
import dayjs from "dayjs";
import { CSVLink } from "react-csv";

const { RangePicker } = DatePicker;

const LogManagement = () => {
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(false);
  const [dateRange, setDateRange] = useState({
    startDate: dayjs().subtract(30, "days").format("YYYY-MM-DD"),
    endDate: dayjs().format("YYYY-MM-DD"),
  });

  const fetchLogs = async () => {
    setLoading(true);
    try {
      const response = await axios.get("http://localhost:5000/api/logs", {
        params: { startDate: dateRange.startDate, endDate: dateRange.endDate },
      });
      setLogs(response.data);
    } catch (error) {
      console.error("Error fetching logs:", error);
      message.error("获取日志失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchLogs();
  }, [dateRange]);

  const columns = [
    { title: "用户名", dataIndex: "username", key: "username" },
    { title: "操作", dataIndex: "event", key: "event" },
    { title: "时间", dataIndex: "timestamp", key: "timestamp", render: (text) => dayjs(text).format("YYYY-MM-DD HH:mm:ss") },
  ];

  const csvData = logs.map((log) => ({
    username: log.username,
    event: log.event,
    timestamp: dayjs(log.timestamp).format("YYYY-MM-DD HH:mm:ss"),
  }));

  return (
    <div style={{ padding: "24px" }}>
      <div style={{ marginBottom: "24px", display: "flex", justifyContent: "space-between" }}>
        <RangePicker
          defaultValue={[dayjs().subtract(30, "days"), dayjs()]}
          onChange={(dates, dateStrings) => {
            if (dates) {
              setDateRange({ startDate: dateStrings[0], endDate: dateStrings[1] });
            }
          }}
          style={{ width: "300px" }}
        />
        <CSVLink data={csvData} filename={`logs-${dayjs().format("YYYYMMDD")}.csv`}>
          <Button type="primary">导出日志</Button>
        </CSVLink>
      </div>
      <Table
        columns={columns}
        dataSource={logs}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 10 }}
      />
    </div>
  );
};

export default LogManagement;